package com.achen.service.impl;

import com.achen.dao.PermissionDao;
import com.achen.dao.RoleDao;
import com.achen.dao.UserDao;
import com.achen.pojo.Permission;
import com.achen.pojo.Role;
import com.achen.pojo.User;
import com.achen.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * 用户服务
 * @author achen
 * @create 2020-04-24 1:45
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissonDao;

    @Override
    public User findByUsername(String name) {
        //根据用户名获取用户的基本信息，不包含用户的角色
        User user = userDao.findByUsername(name);
        if(user == null){
            //用户不存在
            return null;
        }
        //根据用户ID查询对应的角色
        Integer userId = user.getId(); //获取用户ID
        Set<Role> roles = roleDao.findByUserId(userId); //角色一般不会重复，这里可以用list
        for (Role role : roles) {
            Integer roleId = role.getId(); //获取角色ID
            //根据角色ID查询相应的权限
            Set<Permission> permissions = permissonDao.findByRoleId(roleId); //用set的目是去重
            role.setPermissions(permissions); //角色关联权限
        }
        //用户关联角色
        user.setRoles(roles);
        return user;
    }
}
